﻿using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace wall
{
    public partial class AdminPanel : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["Admin"] == null)
                {
                    Response.Redirect("AdminLogin.aspx");
                }
                LoadMessages();
            }
        }

        private void LoadMessages()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string query = "SELECT Id, Username, Message, DatePosted, AdminReply FROM Messages WHERE IsDeleted = 0";
                SqlCommand command = new SqlCommand(query, connection);

                try
                {
                    connection.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    System.Data.DataTable dt = new System.Data.DataTable();
                    adapter.Fill(dt);
                    gvMessages.DataSource = dt;
                    gvMessages.DataBind();
                }
                catch (Exception ex)
                {
                    Response.Write("发生错误：" + ex.Message);
                }
            }
        }

        protected void gvMessages_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int messageId = Convert.ToInt32(e.CommandArgument);

            if (e.CommandName == "Delete")
            {
                DeleteMessage(messageId);
            }
            else if (e.CommandName == "Reply")
            {
                Response.Redirect($"ReplyMessage.aspx?MessageId={messageId}");
            }
        }

        private void DeleteMessage(int messageId)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string query = "UPDATE Messages SET IsDeleted = 1 WHERE Id = @Id";
                SqlCommand command = new SqlCommand(query, connection);
                command.Parameters.AddWithValue("@Id", messageId);

                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
                    LoadMessages();
                }
                catch (Exception ex)
                {
                    Response.Write("发生错误：" + ex.Message);
                }
            }
        }
    }
}
